"""
GitCode MCP客户端示例

演示如何使用MCP客户端连接到GitCode MCP服务器
"""
import asyncio
import os
import sys

from mcp import ClientSession, StdioServerParameters, types
from mcp.client.stdio import stdio_client
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()


async def run_client():
    """运行MCP客户端"""
    # 配置服务器参数
    server_params = StdioServerParameters(
        command=sys.executable,  # 使用当前Python解释器
        args=["-m", "gitcode_mcp"],  # 命令行参数
        env={"GITCODE_TOKEN": os.environ.get("GITCODE_TOKEN")},  # 环境变量
    )
    
    # 连接到服务器
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            # 初始化连接
            await session.initialize()
            print("已连接到GitCode MCP服务器")
            
            # 列出可用的工具
            tools_result = await session.list_tools()
            print(f"\n可用工具数量: {len(tools_result.tools)}")
            for tool in tools_result.tools:
                print(f"  - {tool.name}: {tool.description}")
            
            # 列出可用的资源
            resources_result = await session.list_resources()
            print(f"\n可用资源数量: {len(resources_result.resources)}")
            for resource in resources_result.resources:
                print(f"  - {resource.uri}")
            
            # 列出可用的提示模板
            prompts_result = await session.list_prompts()
            print(f"\n可用提示模板数量: {len(prompts_result.prompts)}")
            for prompt in prompts_result.prompts:
                print(f"  - {prompt.name}: {prompt.description}")
            
            # 演示调用工具
            try:
                print("\n获取用户仓库列表:")
                result = await session.call_tool("list_repositories", arguments={})
                # result.content 是一个列表，包含文本或其他内容
                if result.content:
                    for content_item in result.content:
                        if hasattr(content_item, 'text'):
                            print(content_item.text[:500])  # 只显示前500个字符
                        else:
                            print(content_item)
            except Exception as e:
                print(f"调用工具时出错: {e}")
                import traceback
                traceback.print_exc()


def main():
    """主函数"""
    try:
        asyncio.run(run_client())
    except KeyboardInterrupt:
        print("\n程序已中断")
    except Exception as e:
        print(f"错误: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)


if __name__ == "__main__":
    main() 